//
//  ValuePickerControlelr.swift
//  SitPosition
//
//  Created by apple on 2019/1/19.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography


/**
 * 单选列表值选择器
 */
class ValuePickerControlelr<T: Equatable & Hashable> : UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    // MARK: - Properties
    
    // 拿到值时的处理回调
    // idx: 选中的值索引
    // value: 选中的值
    public var onGotValue: (_ idx: Int, _ value: T?) -> Void = { _, _ in }
    // 高级设置回调
    public var onAdvanceSetting: (() -> Void)? = nil {
        didSet {
            advanceSettingBtn.isHidden = onAdvanceSetting == nil
        }
    }
    // 数据源
    public var selectedRow: Int = 0 {
        didSet {
            guard selectedRow >= 0 else { return }
            picker.selectRow(selectedRow, inComponent: 0, animated: true)
        }
    }
    public var items: [(title: String, value: T)] = [] {
        didSet {
            picker.reloadAllComponents()
        }
    }
    
    // 面板
    private var panel: UIView = UIView.colored(UIColor.white)
    
    // 高级设置按钮
    private lazy var advanceSettingBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.primaryBlueColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 14)
        btn.addTarget(self, action: #selector(_handleAdvanceSetting), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.studySettingAdvanceSetting, for: UIControl.State.normal)
        btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
        btn.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top
        btn.isHidden = true
        return btn
    }()
    
    // Picker
    private lazy var picker: UIPickerView = {
        let view = UIPickerView()
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    // 确定、取消按钮
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.lighgrayTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleCancel), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.cancel, for: UIControl.State.normal)
        return btn
    }()
    
    private let horSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    private let verSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    
    private lazy var okBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.primaryBlueTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleOk), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.ok, for: UIControl.State.normal)
        return btn
    }()
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        // 子视图
        panel.addSubviews([picker, advanceSettingBtn, horSeperator, cancelBtn, verSeperator, okBtn])
        view.addSubview(panel)
        _setupConstraints()
        
        // 手势
        let tapableView: UIView = {
            let view = UIView()
            view.backgroundColor = UIColor.clear
            return view
        }()
        view.insertSubview(tapableView, at: 0)
        constrain(tapableView, view) { v, parent in
            v.edges == parent.edges
        }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(_handleCancel))
        tapableView.addGestureRecognizer(tapGesture)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 动效
        panel.transform = CGAffineTransform.init(translationX: 0, y: 275)
        UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity:0.5, options: UIView.AnimationOptions.preferredFramesPerSecond60, animations: { [weak self] in
            self?.panel.transform = .identity
        }, completion: nil)
    }
    
    // MARK: - Private Methods

    // 取消
    @objc func _handleCancel() {
        onGotValue(selectedRow, nil)
    }
    
    // 确定
    @objc func _handleOk() {
        guard selectedRow >= 0 else {
            onGotValue(selectedRow, nil)
            return
        }
        onGotValue(selectedRow, items[selectedRow].value)
    }
    
    // 高级设置
    @objc func _handleAdvanceSetting() {
        onAdvanceSetting?()
    }

    // 设置视图约束
    func _setupConstraints() {
        let pickerH: CGFloat = 191
        let buttonH: CGFloat = 50
        
        // panel
        constrain(panel, view) { v, parent in
            let height: CGFloat = pickerH+buttonH
            v.bottom == parent.bottom
            v.left == parent.left
            v.right == parent.right
            if #available(iOS 11.0, *) {
                v.top == parent.safeAreaLayoutGuide.bottom - height
            } else {
                v.height == height
            }
        }
        
        // advanceSettingBtn
        constrain(advanceSettingBtn, panel) { (v, parent) in
            v.top == parent.top+6
            v.right == parent.right-10
            v.width == 120
            v.height == 32
        }
        
        // picker
        constrain(picker, panel) { v, parent in
            v.top == parent.top
            v.left == parent.left
            v.right == parent.right
            v.height == pickerH
        }
        
        constrain(horSeperator, picker, panel) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.right == parent.right
            v.height == 1
        }
        
        // button(s)
        constrain(cancelBtn, horSeperator, panel) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.width == parent.width / 2 - 0.5
            v.height == buttonH-1
        }
        
        constrain(verSeperator, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.centerX == parent.centerX
            v.width == 1
            v.bottom == parent.bottom
        }
        
        constrain(okBtn, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.right == parent.right
            v.width == sibling.width
            v.height == sibling.height
        }
    }

    // MARK: - UIPickerViewDataSource / UIPickerViewDelegate
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items.count
    }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let s: String = items[row].title
        var attributes: [NSAttributedString.Key : Any] = [
            .font : Theme.Font.regularFont(ofSize: 22)
        ]
        if row == selectedRow {
            attributes[.foregroundColor] = Theme.Color.deepDarkTextColor
        } else {
            attributes[.foregroundColor] = Theme.Color.deepgrayTextColor
        }
        return NSAttributedString(string: s, attributes: attributes)
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedRow = row
        picker.reloadAllComponents()
    }
}
